package io.gitee.minelx.commontools;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class IOUtil {

	private static final int BUFFER_LENGTH_DEFAULT = 512;

	public static void exchange(InputStream inputStream, OutputStream output, int bufferLength) throws IOException {
		byte[] buffer = new byte[bufferLength];
		int len;
		while ((len = inputStream.read(buffer)) != -1) {
			output.write(buffer, 0, len);
		}
		output.flush();
	}

	public static void exchange(InputStream inputStream, OutputStream output) throws IOException {
		exchange(inputStream, output, BUFFER_LENGTH_DEFAULT);
	}

	public static String stringOf(InputStream inputStream, Charset charset) throws IOException {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		exchange(inputStream, outputStream);
		return outputStream.toString(charset.name());
	}

	public static byte[] bytesOf(InputStream inputStream) throws IOException {
		ByteArrayOutputStream result = new ByteArrayOutputStream();
		exchange(inputStream, result);
		return result.toByteArray();
	}
}
